package com.jamaskii.ecdict;

import com.jamaskii.utils.IOUtils;

import java.util.ArrayList;

public class WordBook {
    public String name;
    public String last;
    public int times=0;
    public ArrayList<Word> words=new ArrayList<>();

    public String error;

    public boolean save(String path){
        String fileName = path+"/"+name+".wb";
        if(!IOUtils.checkFile(fileName)){
            IOUtils.println(fileName);
            error="CreateFileFailed";
            return false;
        }
        else{
            return IOUtils.fileWriteString(fileName, this.dumps());
        }
    }

    public String dumps(){
        if(name==null){
            return null;
        }
        if(last==null){last=" ";}
        String dump=name+"#gap#"+times+"#gap#"+last;
        for (Word word:words
        ) {
            if(word==null){
                continue;
            }
            dump+="\n";
            String append=word.dumps();
            if(append==null){
                continue;
            }
            dump+=append;
        }
        return dump;
    }

    public static WordBook loads(String fileName){
        WordBook wordBook =new WordBook();
        String nodes[]=fileName.split("/");
        wordBook.name=nodes[nodes.length-1].replace(".wb", "");
        String[] lines = IOUtils.readFileString(fileName).split("\n");
        int i=0;
        while (i<lines.length){
            if(i==0){
                String[] info=lines[i].split("#gap#");
                //HomeActivity.instance.showMessage(info.length+"");
                if(info.length==3){
                    wordBook.name=info[0];
                    if(!info[1].equals("")){
                        wordBook.times=Integer.parseInt(info[1]);
                    }
                    wordBook.last=info[2];
                }else{
                    return null;
                }
            }
            else{
                wordBook.words.add(Word.loads(lines[i]));
            }
            i++;
        }
        return wordBook;
    }

    public boolean isExist(Word word){
        return isExist(word.name);
    }

    public boolean isExist(String word){
        for (Word one:words
        ) {
            if(word.equals(one.name)){
                return true;
            }
        }
        return false;
    }

}
